
/**
 * 鼠标悬停出现滚动条
 */
import React, { useRef, useEffect,forwardRef,useImperativeHandle } from "react"
import "./index.scss"
function HoverScrollComp(props: {
    children: React.ReactNode,
    height: string;
    onScroll: (e: React.UIEvent<HTMLDivElement, UIEvent>) => void;
},ref: React.Ref<unknown>) { 
    const cutboxRef = useRef<HTMLDivElement>(null)
    const boxRef = useRef<HTMLDivElement>(null)
    const resizeFn = () => { 
        const cutBoxWidth = (cutboxRef.current as HTMLDivElement).offsetWidth;
        (boxRef.current as HTMLDivElement).style.width = `${cutBoxWidth - 5}px`
    }
    useEffect(() => { 
        window.addEventListener('resize',resizeFn)
        resizeFn()
    }, [])
    const autoScrollTop = (scrollTop?:number) => { 
        const messageBox = cutboxRef.current as HTMLDivElement
        messageBox.scrollTop = scrollTop || messageBox.scrollHeight
    }
    // 使用 useImperativeHandle 来将方法暴露给父组件
    useImperativeHandle(ref, () => ({
        cutboxRef,
        autoScrollTop,
    }));
    return (
        <div className="hoverScroll" style={{
            height:props.height
        }} ref={ cutboxRef} onScroll={props.onScroll}>
            <div className="hoverScrollContent" ref={ boxRef}>
                { props.children}
            </div>
        </div>
    )
}

export  const HoverScroll = forwardRef(HoverScrollComp)